const router = require('koa-router')()
const path = require('path')
const fs = require('fs')

// 获取所有评论
router.get('/getcomment', async function (ctx, next) {
    let sql = 'select * from user.method method join user.comment comment on method.id = comment.passageId join user.user user on user.id=comment.userId'
    let result = await ctx.db.EXCUTE(sql);
    for (let i in result) {
        if (result[i].userImage != null) {
            let header = result[i].userImage.split('/')[0];
            if (header == '..') {
                let arr1 = result[i].userImage.split('/');
                let arr2 = arr1.splice(2, 4)
                arr2 = arr2.join('/')
                //绝对地址
                let filePath = path.join(__dirname, '../../../小程序/', arr2)
                let fileObj = fs.readFileSync(filePath);
                let file = fileObj.toString('base64');
                let imgUrl = `data:image/png;base64,${file}`
                result[i].userImage = imgUrl;
            }
        }
    }
    ctx.body = { data: result, status: "获取评论信息成功" }
})

// 查询评论
router.post('/selcomment', async function (ctx, next) {
    let keyword = ctx.request.body.keyword;
    let sql = `select * from user.method method join user.comment comment on method.id = comment.passageId join user.user user on user.id=comment.userId where username like "%${keyword}%" or title like "%${keyword}%"`
    let result = await ctx.db.EXCUTE(sql);
    if (result == '') {
        ctx.body = { status: "没有评论" }
    } else {
        for (let i in result) {
            if (result[i].userImage != null) {
                let header = result[i].userImage.split('/')[0];
                if (header == '..') {
                    let arr1 = result[i].userImage.split('/');
                    let arr2 = arr1.splice(2, 4)
                    arr2 = arr2.join('/')
                    //绝对地址
                    let filePath = path.join(__dirname, '../../../小程序/', arr2)
                    let fileObj = fs.readFileSync(filePath);
                    let file = fileObj.toString('base64');
                    let imgUrl = `data:image/png;base64,${file}`
                    result[i].userImage = imgUrl;
                }
            }
        }
        ctx.body = { data: result, status: "查找评论成功" }
    }
})

// 删除某条评论
router.post('/delcomment', async function (ctx, next) {
    const unid = ctx.request.body.unid
    let sql = `delete from comment where unid = "${unid}"`
    await ctx.db.EXCUTE(sql);
    ctx.body = { status: "删除评论成功" }
})

module.exports = router
